<?php
	require_once('./config.php');
	require_once('./network.php');
	require_once('./security.php');

	$token=GetToken();

	if(!$token)
	{
		$error='Need Authorization';//错误信息:需要验证
		FailFeed($error);
	}
	else
	{
		for($i=0;$i<$network_max_try;$i++)
		{
			$response=GetFeed($token);
			if($response['http_code']!=502)
				break;
		}
		
		if($response['http_code']==200)
		{
			$head	=	'<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" .
							'<rss version="2.0">' . "\r\n" .
							'	<channel>' . "\r\n";
			if(isset($_GET['type']) && $_GET['type']=='mentions')
				$head	.=	'		<title>Twitter / Mentions</title>' . "\r\n" .
								'		<link>https://twitter.com/mentions</link>' . "\r\n" .
								'		<description>Twitter Replies</description>' . "\r\n";
			else
				$head	.=	'		<title>Twitter / Home Timeline</title>' . "\r\n" .
								'		<link>https://twitter.com/</link>' . "\r\n" .
								'		<description>Twitter updates and retweets</description>' . "\r\n";
			$head	.=	 '		<language>en-us</language>' . "\r\n";

			OutputRSS($head, $response['content']);
		}
		else
		{
			$error=$response['http_code'] . '<br />' . htmlentities($response['content'], ENT_QUOTES, 'UTF-8', FALSE);
			FailFeed($error);
		}
	}

	function FailFeed($error)//Feed输出错误信息
	{
		global $base_url;

		$time=gmdate('r');
		$output="<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<rss version=\"2.0\">\r\n<channel>\r\n<title>Twitter Feed</title>\r\n<link>$base_url</link>\r\n<pubDate>$time</pubDate>\r\n<language>en-us</language>\r\n<item>\r\n<title>Twitter Feed Error</title>\r\n<description>\r\n<![CDATA[\r\n$error\r\n]]>\r\n</description>\r\n<pubDate>$time</pubDate>\r\n<guid>$time</guid>\r\n<link>$base_url</link>\r\n</item>\r\n</channel>\r\n</rss>\r\n";

		header('Content-Type: application/rss+xml; charset=utf-8');
		print($output);

		return 0;
	}

	function GetFeed($token)
	{
		global $oauth_signature_method, $oauth_version, $api_url, $consumer_key, $consumer_secret;

		$oauth_timestamp=time();
		$oauth_nonce=$oauth_timestamp;

		$oauth_param=array('oauth_consumer_key'=>$consumer_key, 'oauth_token'=>$token['oauth_token'], 'oauth_signature_method'=>$oauth_signature_method, 'oauth_timestamp'=>$oauth_timestamp, 'oauth_nonce'=>$oauth_nonce, 'oauth_version'=>$oauth_version);
		foreach($oauth_param as $key => $val)
			$oauth_param[$key]=urlencode($val);

		$method='GET';

		$url=$api_url;
		if(isset($_GET['type']) && $_GET['type']=='mentions')
			$url .= 'statuses/mentions';
		else
			$url .= 'statuses/home_timeline';
		$url .= '.json';
		
		$secret=$consumer_secret . '&' . $token['oauth_token_secret'];

		$qurry_param=NULL;
		//处理Feed参数,需要urlencode
		if(isset($_GET['since_id']))
			$qurry_param['since_id']=$_GET['since_id'];
		if(isset($_GET['max_id']))
			$qurry_param['max_id']=$_GET['max_id'];
		if(isset($_GET['count']))
			$qurry_param['count']=$_GET['count'];
		if(isset($_GET['page']))
			$qurry_param['page']=$_GET['page'];
		$qurry_param['include_entities']='true';
		if($qurry_param!=NULL)
			foreach($qurry_param as $key => $val)
			$qurry_param[$key]=urlencode($val);

		$response=TwitterHttp($method, $url, $oauth_param, $secret, $qurry_param);

		return $response;
	}

	function OutputRSS($head, $json)
	{
		header('Content-Type: application/rss+xml; charset=utf-8');
		print($head);

		$json=json_decode($json, true);
		if(isset($json))
		{
			foreach($json as $val)
			{
				$item=CreateItem($val);
				print($item);
			}
		}

		$rss	=	'	</channel>' . "\r\n" .
					'</rss>' . "\r\n";
		print($rss);

		return 0;
	}

	function CreateItem($val)
	{
		$item='		<item>' . "\r\n";
		if(isset($val['retweeted_status']))//RT
		{
			$item .= '			<title><![CDATA[' . $val['retweeted_status']['user']['screen_name'] . '(' . $val['retweeted_status']['user']['name'] . ') Retweeted by ' . $val['user']['screen_name'] . '(' . $val['user']['name'] . ')]]></title>' . "\r\n";
			$item .= '			<description><![CDATA[' . $val['retweeted_status']['text'] . ']]></description>' . "\r\n";
		}
		else
		{
			if(isset($val['in_reply_to_screen_name']))//@
			{
				$user='';
				foreach($val['entities']['user_mentions'] as $v)
					if($v['id']==$val['in_reply_to_user_id'])
					{
						$user=$val['in_reply_to_screen_name'] . '(' . $v['name'] . ')';
						break;
					}
				$item .= '			<title><![CDATA[' . $val['user']['screen_name'] . '(' . $val['user']['name'] . ') Reply to ' . $user . ']]></title>' . "\r\n";
			}
			else//normal
				$item .= '			<title><![CDATA[' . $val['user']['screen_name'] . '(' . $val['user']['name'] . ')]]></title>' . "\r\n";
			$item .= '			<description><![CDATA[' . $val['text'] . ']]></description>' . "\r\n";
		}
		//$date=DateTime::createFromFormat('D M d H:i:s O Y',  $val['created_at']);
		//$item .= '			<pubDate>' .$date->format('r') . '</pubDate>' . "\r\n";
		date_default_timezone_set('UTC');
		$date=strtotime($val['created_at']);
		$item .= '			<pubDate>' . gmdate('r', $date) . '</pubDate>' . "\r\n";
		$item .= '			<author><![CDATA[' . $val['user']['name'] . ']]></author>' . "\r\n";
		$item .= '			<guid>https://twitter.com/' . $val['user']['screen_name'] . '/statuses/' . $val['id_str'] . '</guid>' . "\r\n";
		$item .= '			<link>https://twitter.com/' . $val['user']['screen_name'] . '/statuses/' . $val['id_str'] . '</link>' . "\r\n";
		$item .= '		</item>' . "\r\n";

		return $item;
	}
?>